import request from '@/utils/request'

// GPU监控相关API接口

/**
 * 获取GPU状态信息
 * @returns {Promise}
 */
export function getGpuStatus() {
  return request({
    url: '/api/v1/gpu/status',
    method: 'get'
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: formatGpuStatusResponse(response)
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取GPU使用率历史数据
 * @param {Object} query 查询参数
 * @returns {Promise}
 */
export function getGpuUsageHistory(query = {}) {
  const params = {
    start_time: query.startTime || query.start_time,
    end_time: query.endTime || query.end_time,
    interval: query.interval || '1m',
    gpu_id: query.gpuId || query.gpu_id
  }

  // 移除undefined值
  Object.keys(params).forEach(key => {
    if (params[key] === undefined || params[key] === '') {
      delete params[key]
    }
  })

  return request({
    url: '/api/v1/gpu/usage/history',
    method: 'get',
    params: params
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取GPU详细信息
 * @param {string|number} gpuId GPU ID
 * @returns {Promise}
 */
export function getGpuDetail(gpuId) {
  return request({
    url: `/api/v1/gpu/${gpuId}`,
    method: 'get'
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: formatGpuDetailResponse(response)
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取GPU进程信息
 * @param {string|number} gpuId GPU ID
 * @returns {Promise}
 */
export function getGpuProcesses(gpuId) {
  return request({
    url: `/api/v1/gpu/${gpuId}/processes`,
    method: 'get'
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取GPU温度历史数据
 * @param {Object} query 查询参数
 * @returns {Promise}
 */
export function getGpuTemperatureHistory(query = {}) {
  const params = {
    start_time: query.startTime || query.start_time,
    end_time: query.endTime || query.end_time,
    interval: query.interval || '1m',
    gpu_id: query.gpuId || query.gpu_id
  }

  // 移除undefined值
  Object.keys(params).forEach(key => {
    if (params[key] === undefined || params[key] === '') {
      delete params[key]
    }
  })

  return request({
    url: '/api/v1/gpu/temperature/history',
    method: 'get',
    params: params
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取GPU内存使用历史数据
 * @param {Object} query 查询参数
 * @returns {Promise}
 */
export function getGpuMemoryHistory(query = {}) {
  const params = {
    start_time: query.startTime || query.start_time,
    end_time: query.endTime || query.end_time,
    interval: query.interval || '1m',
    gpu_id: query.gpuId || query.gpu_id
  }

  // 移除undefined值
  Object.keys(params).forEach(key => {
    if (params[key] === undefined || params[key] === '') {
      delete params[key]
    }
  })

  return request({
    url: '/api/v1/gpu/memory/history',
    method: 'get',
    params: params
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 获取GPU性能统计
 * @returns {Promise}
 */
export function getGpuStatistics() {
  return request({
    url: '/api/v1/gpu/statistics',
    method: 'get'
  }).then(response => {
    return {
      code: 200,
      msg: '查询成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 重置GPU
 * @param {string|number} gpuId GPU ID
 * @returns {Promise}
 */
export function resetGpu(gpuId) {
  return request({
    url: `/api/v1/gpu/${gpuId}/reset`,
    method: 'post'
  }).then(response => {
    return {
      code: 200,
      msg: '重置成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 设置GPU功率限制
 * @param {string|number} gpuId GPU ID
 * @param {number} powerLimit 功率限制(瓦特)
 * @returns {Promise}
 */
export function setGpuPowerLimit(gpuId, powerLimit) {
  return request({
    url: `/api/v1/gpu/${gpuId}/power-limit`,
    method: 'post',
    data: {
      power_limit: powerLimit
    }
  }).then(response => {
    return {
      code: 200,
      msg: '设置成功',
      data: response
    }
  }).catch(error => {
    throw formatErrorResponse(error)
  })
}

/**
 * 格式化GPU状态响应数据
 * @param {Object} gpuStatus 后端GPU状态数据
 * @returns {Object} 前端格式的GPU状态数据
 */
function formatGpuStatusResponse(gpuStatus) {
  if (!gpuStatus) return null

  // 如果是数组，处理多个GPU
  if (Array.isArray(gpuStatus)) {
    return gpuStatus.map(gpu => formatSingleGpuStatus(gpu))
  }

  // 单个GPU
  return formatSingleGpuStatus(gpuStatus)
}

/**
 * 格式化单个GPU状态
 * @param {Object} gpu GPU数据
 * @returns {Object} 格式化的GPU数据
 */
function formatSingleGpuStatus(gpu) {
  return {
    id: gpu.id,
    name: gpu.name,
    uuid: gpu.uuid,
    usage: {
      gpu: gpu.gpu_usage || gpu.usage?.gpu || 0,
      memory: gpu.memory_usage || gpu.usage?.memory || 0,
      encoder: gpu.encoder_usage || gpu.usage?.encoder || 0,
      decoder: gpu.decoder_usage || gpu.usage?.decoder || 0
    },
    memory: {
      total: gpu.memory_total || gpu.memory?.total || 0,
      used: gpu.memory_used || gpu.memory?.used || 0,
      free: gpu.memory_free || gpu.memory?.free || 0
    },
    temperature: {
      current: gpu.temperature || gpu.temp?.current || 0,
      max: gpu.temperature_max || gpu.temp?.max || 0
    },
    power: {
      current: gpu.power_draw || gpu.power?.current || 0,
      limit: gpu.power_limit || gpu.power?.limit || 0,
      max: gpu.power_max || gpu.power?.max || 0
    },
    fan: {
      speed: gpu.fan_speed || gpu.fan?.speed || 0
    },
    processes: gpu.processes || [],
    status: gpu.status || 'active',
    driver_version: gpu.driver_version,
    cuda_version: gpu.cuda_version
  }
}

/**
 * 格式化GPU详细信息响应数据
 * @param {Object} gpuDetail 后端GPU详细数据
 * @returns {Object} 前端格式的GPU详细数据
 */
function formatGpuDetailResponse(gpuDetail) {
  if (!gpuDetail) return null

  return {
    ...formatSingleGpuStatus(gpuDetail),
    specifications: {
      architecture: gpuDetail.architecture,
      compute_capability: gpuDetail.compute_capability,
      multiprocessors: gpuDetail.multiprocessors,
      cores_per_multiprocessor: gpuDetail.cores_per_multiprocessor,
      total_cores: gpuDetail.total_cores,
      base_clock: gpuDetail.base_clock,
      boost_clock: gpuDetail.boost_clock,
      memory_clock: gpuDetail.memory_clock,
      memory_bus_width: gpuDetail.memory_bus_width,
      memory_bandwidth: gpuDetail.memory_bandwidth
    },
    performance: {
      compute_performance: gpuDetail.compute_performance,
      memory_performance: gpuDetail.memory_performance,
      efficiency_score: gpuDetail.efficiency_score
    }
  }
}

/**
 * 格式化错误响应
 * @param {Object} error 错误对象
 * @returns {Object} 格式化的错误
 */
function formatErrorResponse(error) {
  if (error.response && error.response.data) {
    const errorData = error.response.data
    return {
      code: error.response.status || 500,
      msg: errorData.message || errorData.detail || '操作失败',
      data: null
    }
  }
  return {
    code: 500,
    msg: error.message || '网络错误',
    data: null
  }
}

// 导出API对象
export const gpuApi = {
  getStatus: getGpuStatus,
  getUsageHistory: getGpuUsageHistory,
  getDetail: getGpuDetail,
  getProcesses: getGpuProcesses,
  getTemperatureHistory: getGpuTemperatureHistory,
  getMemoryHistory: getGpuMemoryHistory,
  getStatistics: getGpuStatistics,
  reset: resetGpu,
  setPowerLimit: setGpuPowerLimit
}

// 默认导出
export default gpuApi

// GPU状态常量
export const GpuStatus = {
  ACTIVE: 'active',
  IDLE: 'idle',
  ERROR: 'error',
  MAINTENANCE: 'maintenance'
}

// GPU使用率阈值常量
export const GpuThresholds = {
  USAGE: {
    LOW: 30,
    MEDIUM: 70,
    HIGH: 90
  },
  TEMPERATURE: {
    NORMAL: 60,
    WARNING: 80,
    CRITICAL: 90
  },
  MEMORY: {
    LOW: 50,
    MEDIUM: 80,
    HIGH: 95
  }
}